package com.vf.cloud.paas.app.master.api.sys.controller;

import java.util.concurrent.TimeUnit;

import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.kit.StrKit;
import com.vf.cloud.paas.app.master.common.domain.User;
import com.vf.cloud.paas.common.constant.SecurityConstant;
import com.vf.cloud.paas.common.datasource.annotation.Tx;
import com.vf.cloud.paas.common.log.annotation.RLog;
import com.vf.cloud.paas.common.service.IRedis;
import com.vf.cloud.paas.common.util.EncryptUtil;
import com.vf.cloud.paas.common.util.JWTUtil;
import com.vf.cloud.paas.common.util.R;
import com.vf.cloud.paas.common.util.RsaUtil;
import lombok.RequiredArgsConstructor;

@RequiredArgsConstructor
@RestController
@RequestMapping("/api/v1/auth")
public class AuthController {

	@Autowired
	private IRedis redisImpl;

	@RLog(value = "登录PaaS", type = "user")
	@Tx
	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public R<String> login(@RequestBody User param) {
		try {
			if (param == null || StrKit.isBlank(param.getPassword()) || StrKit.isBlank(param.getUsername())) {
				return R.failed("账号密码必填.");
			}

			String username = "";
			String password = "";
			try {
				username = RsaUtil.decrypt(param.getUsername(), SecurityConstant.PRIVATE_KEY);
				password = RsaUtil.decrypt(param.getPassword(), SecurityConstant.PRIVATE_KEY);
			} catch (Exception e) {
				e.printStackTrace();
				return R.failed("解密登录信息失败!");
			}

			User user = User.dao.findFirst("select * from master_user where username=?", username);
			if (user == null) {
				return R.failed("用户名或密码错误.");
			}

			if (!EncryptUtil.matches(password, user.getPassword())) {
				return R.failed("用户名或密码错误.");
			}

			String token = JWTUtil.generateToken(user.getId(), user.getUsername());
			redisImpl.add(token, JSONObject.toJSONString(user), JWTUtil.getExpiresAt(token).getTime(),
					TimeUnit.MILLISECONDS);
			return R.ok(SecurityConstant.TOKEN_SPLIT + token);
		} catch (Exception e) {
			return R.failed(e.getMessage());
		}
	}

	@RLog(value = "登出PaaS", type = "user")
	@Tx
	@RequestMapping(value = "/logout", method = RequestMethod.DELETE)
	public R<String> logout(HttpServletRequest request) {
		try {
			String token = request.getHeader(SecurityConstant.HEADER);
			token = token.replace(SecurityConstant.TOKEN_SPLIT, "");
			redisImpl.delete(token);
			return R.ok("用户已经注销！");
		} catch (Exception e) {
			return R.ok("用户已经注销！");
		}
	}

}
